package top.lingkang.mm.page;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * postgresql 下的分页处理.使用LIMIT和OFFSET子句
 *
 * @author lingkang
 * @create by 2024/3/11 12:17
 */
public class PageSqlHandlePostgreSql implements PageSqlHandle {
    @Override
    public PageSqlInfo handleSql(String selectSql, int page, int size) {
        String sql = selectSql.toLowerCase();

        int index = sql.indexOf("from");
        int start = sql.substring(0, index).indexOf("(");
        while (start != -1) {
            start = sql.indexOf("(", start + 1);
            if (start == -1)
                index = sql.indexOf("from", index + 1);
        }

        // 匹配排序，可能存在排序，需要特殊处理
        Matcher matcher = orderBy.matcher(sql);
        PageSqlInfo info = new PageSqlInfo();
        if (matcher.find())
            info.setCountSql("select count(*) " + selectSql.substring(index, matcher.start()));
        else
            info.setCountSql("select count(*) " + selectSql.substring(index));

        info.setSelectSql(selectSql + " limit " + size + " offset " + (page - 1) * size);
        return info;
    }
}
